//相当于通用分页查询的实现
import { IHooksOptions } from '@/hooks/hooksinterface'
import { onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'


//编写一个方法，实现查询，删除，导出excel等通用操作
export const useCrud = (options : IHooksOptions) => {

    //默认接口初始化变量赋值
    const defaultOptions : IHooksOptions = {
        createdIsNeed: true,
        isPage: true,
        queryApi: undefined,
        deleteApi: undefined,
        primaryKey: 'id',
        exportApi: undefined,
        //日期查询条件
        dateRange: [],
        queryParams: {},
        rows: [],
        total: 0,
        order: '',
        asc: 'ascending',
        pageNum: 1,
        pageSize: 10,
        pageSizes: [5, 10, 20, 30, 50, 100, 200],
        loading: false,
        selections: [],
        // 默认不启用编辑按钮
        single: true,
        // 默认不启用删除按钮
        multiple: true,
        //要不要显示搜索条件
        showSearch: true,
        ids: []
    }

    // 合并用户配置（options:默认值，props：用户自己的值）
    const mergeDefaultOptions = (options : any, props : any) : IHooksOptions => {
        for (const key in options) {
            if (!Object.getOwnPropertyDescriptor(props, key)) {
                props[key] = options[key]
            }
        }
        return props
    }

    // 覆盖默认值
    const state = mergeDefaultOptions(defaultOptions, options)

    //页面加载完成以后，判断是否要执行分页查询操作
    onMounted(() => {
        if (state.createdIsNeed) {
            query()
        }
    })

    /**
     * 查询方法
     */
    const query = () => {
        //如果你没有配置queryApi
        if (!state.queryApi) {
            ElMessage.error('请先配置queryApi的接口')
            return
        }

        //动画效果
        state.loading = true

        //查询条件
        const params = {
            orderByColumn: state.order,
            isAsc: state.asc,
            ...state.queryParams
        };
        //日期
        if (state.dateRange && Array.isArray(state.dateRange) && state.dateRange.length === 2) {
            params.beginTime = state.dateRange[0]
            params.endTime = state.dateRange[1]
        }
        //如果是分页
        if (state.isPage) {
            params.pageNum = state.pageNum
            params.pageSize = state.pageSize
        }
        //查询
        state.queryApi(params).then((res : any) => {
            state.rows = state.isPage ? res.data.list : res.data
            state.total = state.isPage ? res.data.total : 0
        })

        state.loading = false
    }

    /**
     * 点击搜索按钮执行操作
     */
    const getDataList = () => {
        if (state.isPage) {
            state.pageNum = 1
        }
        query()
    }


    // 多选
    const selectionChangeHandle = (selections : any[]) => {
        state.selections = selections
        state.ids = selections.map((item : any) => state.primaryKey && item[state.primaryKey])

        // 修改按钮禁用值判断
        state.single = selections.length !== 1;
        // 删除按钮禁用值判断
        state.multiple = selections.length === 0;

    }

    // 排序
    const sortChangeHandle = (data : any) => {
        const { prop, order } = data

        if (prop && order) {
            state.order = prop
            state.asc =order
        } else {
            state.order = ''
        }

        query()
    }

    // 删除事件(给table表中操作删除用的)
    const deleteHandle = (key : number | string) => {
        if (!state.deleteApi) {
            ElMessage.error('请先配置deleteApi的接口')
            return
        }

        ElMessageBox.confirm('确定进行删除操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                if (state.deleteApi) {
                    state.deleteApi([key]).then(() => {
                        ElMessage.success('删除成功')
                        query()
                    })
                }

            })
            .catch(() => { })
    }

    /**
     * 批量删除
     */
    const deleteBatchHandle = (key ?: number | string) => {
        let data : any[] = []
        if (key) {
            data = [key]
        } else {
            data = state.selections ? state.selections : []

            if (data.length === 0) {
                ElMessage.warning('请选择删除记录')
                return
            }
        }

        ElMessageBox.confirm('确定进行删除操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                if (state.deleteApi) {
                    state.deleteApi(data).then(() => {
                        ElMessage.success('删除成功')
                        query()
                    })
                }
            })
            .catch(() => { })
    }


    /**
     * 点击查询重置按钮
     */
    function resetQuery(proxy : any, queryFormName : string = 'queryRef') {
        state.dateRange = [];
        // utils/ruoyi.ts
        proxy?.resetForm(queryFormName);
        //查询一次
        getDataList();
    }

    return { query, getDataList, selectionChangeHandle, sortChangeHandle, resetQuery, deleteHandle, deleteBatchHandle }
}
